import React, { forwardRef, useState, useEffect } from "react";
import { Form, Select, Input, Button, DatePicker, Space, Table, Checkbox, Tag, message } from '@bytedance/mona-ui';
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import { stopCouponFun } from './couponFunc'

import moment from 'moment';
import 'moment/locale/zh-cn';
// import getGoodsQWorkTEXT from 'data-text:./getGoodsCouponWork.js'
// const workStr = getGoodsQWorkTEXT;
// const workBlob = new Blob([workStr], { type: 'text/javascript;charset=utf-8' });
// const workBlobUrl = URL.createObjectURL(workBlob);
import {
    getCouponList,
} from "@Api/productApi"

moment.locale('zh-cn');
const { Option } = Select;

function SetCoupon(props, ref) {
    const [goodsLoading, setGoodsLoading] = useState(false)
    const [goodsListData, setGoodsListData] = useState([])
    const [pageSize, setPageSize] = useState(50)
    const [goodsDataInfoCont, setGoodsDaraInfoCont] = useState({ total: 0 })
    const [indeterminateGoders, setIndeterminateGoders] = useState(false)
    const [selectAllConter, setSelectAllConter] = useState(false)
    const [selectGoodsKeys, setSelectGoodsKeys] = useState<React.Key[]>([])
    const [stopCoupon, setStopCoupon] = useState(false)

    const dataInfo = {
        page: 1,
        size: 20,
        coupon_info: '',
        coupon_type_group: '0',
        // coupon_biz_type: '0',
        favoured_type: '0',
        status: '3',
        start_apply_time: '',
        end_apply_time: ''
    }
    const [getCouDataInfo, setCouDataInfo] = useState(dataInfo)
    const [couponTime, setCouponTime] = useState(null)
    const [lodinDataStatus, seyLodinDataStatus] = useState(false)
    function getCouponData() {
        setGoodsLoading(true)
        getCouDataInfo.page = 1
        onSelectGoodsKeysChange([])
        seyLodinDataStatus(true)
        getCouponList(getCouDataInfo).then((res: any) => {
            const getallData: any = []
            while ((getCouDataInfo.size * getCouDataInfo.page) < res.total) {
                getCouDataInfo.page++
                // console.log('shearDater', shearDater
                // )
                getallData.push(getCouponList(getCouDataInfo))
            }
            setGoodsDaraInfoCont({ total: res.total })

            Promise.all(getallData).then(resit => {
                const datas: any = res.data

                resit.forEach(resdata => {
                    datas.push(...resdata.data)
                })
                datas.forEach(itembt => {
                    itembt.lodinfo = false
                })

                setGoodsListData(datas)
                setGoodsLoading(false)
                seyLodinDataStatus(false)

            })
        })
    }
    // useEffect(() => {
    //     // console.log('getCouDataInfo', getCouDataInfo == dataInfo)
    //     if(getCouDataInfo == dataInfo) {
    //         getCouponData()
    //     }
    // }, [getCouDataInfo])
    useEffect(() => {
        setSelectGoodsKeys(goodsListData.filter(item => {
            return item.status === 1 || item.status === 3
        }).map(res => res.coupon_meta_id))
    }, [goodsListData])
    useEffect(() => {
        if (!selectGoodsKeys || !selectGoodsKeys.length) {
            setSelectAllConter(false)
            setIndeterminateGoders(false)
            return
        }
        if (selectGoodsKeys.length === goodsListData.filter(item => {
            return item.status === 1 || item.status === 3
        }).length) {
            setSelectAllConter(true)
            setIndeterminateGoders(false)
            return
        }
        setIndeterminateGoders(true)
    }, [selectGoodsKeys])

    const onSelectGoodsKeysChange = (newSelectedRowKeys: React.Key[]) => {

        setSelectGoodsKeys(newSelectedRowKeys);
    };

    interface ColumnPropsType {
        index: number;
        name: string;
    }
    const goodsTitle: ColumnProps<ColumnPropsType>[] = [
        // {
        //     title: 'ID',
        //     key: '0',
        //     dataIndex: 'coupon_meta_id',
        //     align: "center",
        //     ellipsis: true
        // },
        {
            title: '优惠券信息',
            key: '1',
            // dataIndex: 'coupon_name',
            width: 250,
            align: "center",
            ellipsis: true,
            render: (_, record: any) => {
                const tagConter = {
                    color: (record.support_type === 1 || record.support_type === 5) ? 'rgb(25, 102, 255)' : record.support_type === 2 ? 'rgb(212, 132, 88)' : record.support_type === 11 ? 'rgb(108, 38, 253)' : record.support_type === 4 ? 'rgb(255, 92, 0)' : '',
                    title: (record.support_type === 1 || record.support_type === 5) ? '通用优惠券' : record.support_type === 2 ? '涨粉券' : record.support_type === 11 ? '达人专属券' : record.support_type === 4 ? '店铺新人券' : ''
                }
                return (<div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'self-start'
                }}>
                    <div>{record.coupon_name}</div>
                    <div style={{
                        margin: '2px 0',
                        fontSize: 12,
                        color: '#AEAEB2'
                    }}>ID:{record.coupon_meta_id}</div>
                    {tagConter.title && <Tag bordered transparentBg style={{ color: `${tagConter.color}`, border: `1px solid ${tagConter.color}` }}>
                        {tagConter.title}
                    </Tag>}
                </div>)
            }
        },
        {
            title: '内容',
            key: '2',
            // dataIndex: 'price_lower',
            align: "center",
            ellipsis: true,
            render: (_, record: any) => {
                const content = {
                    typeName: '',
                    typeInfo: ''
                }
                switch (record.favoured_type) {
                    case 21:
                        content.typeName = `打 ${record.discount / 10} 折`
                        content.typeInfo = '全店通用-折扣券'
                        break;
                    case 22:
                        content.typeName = `减 ${record.credit / 100} 元`

                        content.typeInfo = '全店通用-立减券'
                        break;
                    case 23:
                        content.typeName = `减 ${record.threshold / 100} 减${record.credit / 100} 元`

                        content.typeInfo = '全店通用-满减券'
                        break;
                    case 41:
                        content.typeName = `打 ${record.discount / 10} 折`
                        content.typeInfo = '指定商品-折扣券'
                        break;
                    case 42:
                        content.typeName = `减 ${record.credit / 100} 元`
                        content.typeInfo = '指定商品-立减'
                        break;
                    case 43:
                        content.typeName = `减 ${record.threshold / 100} 减${record.credit / 100} 元`

                        content.typeInfo = '指定商品-满减'
                        break;
                    default:
                        break;
                }
                return (<div>
                    <div>{content.typeName}</div>
                    <div style={{
                        margin: '2px 0',
                        fontSize: 12,
                        color: '#AEAEB2'
                    }}>{content.typeInfo}</div>
                    {/* {tagConter.title && <Tag bordered transparentBg style={{ color: `${tagConter.color}`, border: `1px solid ${tagConter.color}` }}>
                        {tagConter.title}
                    </Tag>} */}
                </div>


                )
            }
        },
        {
            title: '状态',
            key: '3',
            // dataIndex: 'self_sell_stock_num',
            align: "center",
            render: (_, record: any) => {

                return (<div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center'
                }}>
                    {record.status === 1 ? '未生效' : record.status === 2 ? '已作废' : record.status === 3 ? '生效中' : '已过期'}
                </div>


                )
            }
        },
        {
            title: '领取/发放',
            key: '4',
            // dataIndex: 'sell_num',
            align: "center",
            render: (_, record: any) => {

                return (<div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center'
                }}>
                    {record.total_amount - record.left_amount}/{record.total_amount}
                </div>


                )
            }
        },
        {
            title: '已使用',
            key: '5',
            dataIndex: 'used_amount',
            align: "center",
            // ellipsis: true
        },
        // {
        //     title: '商品状态',
        //     key: '6',
        //     dataIndex: 'tab',
        //     align: "center",
        //     // ellipsis: true
        // },
        {
            title: '操作',
            key: '7',
            // dataIndex: 'birth',
            align: "center",
            render: (_, record: any, index) => {
                return (
                    <Button type="link" loading={record.lodinfo} disabled={record.status === 2 || record.status === 4} onClick={async () => {
                        seyLodinDataStatus(true)
                        // setGoodsLoading(true)
                        setStopCoupon(true)
                        goodsListData[index].lodinfo = true
                        setGoodsListData([...goodsListData])
                        const upAll = await stopCouterFun([record.coupon_meta_id])

                        goodsListData[index].lodinfo = false
                        seyLodinDataStatus(false)
                        // setGoodsLoading(false)
                        setStopCoupon(false)
                        setGoodsListData([...goodsListData])
                        // // setLodinstatus(false)
                        message.success(`已作废券 ${record.coupon_name}`)
                    }}>作废</Button>
                );
            },
        }
    ]
    const goodsSelectKeys: any = {
        columnTitle: (
            <Space direction="vertical" size={1}>
                <Checkbox indeterminate={indeterminateGoders} checked={selectAllConter} onChange={(e) => {
                    // console.log('e', e.target.checked)
                    // console.log('goodsListData', goodsListData)
                    setSelectAllConter(e.target.checked)
                    if (e.target.checked) {
                        onSelectGoodsKeysChange(goodsListData.filter(item => {
                            return item.status === 1 || item.status === 3
                        }).map((item: any) => {
                            return item.coupon_meta_id
                        }))
                    } else {
                        onSelectGoodsKeysChange([])
                    }
                }}></Checkbox>
                <span>{selectGoodsKeys.length}/{goodsDataInfoCont.total}</span>
            </Space>
        ),
        columnWidth: 100,
        selectedRowKeys: selectGoodsKeys,
        onChange: onSelectGoodsKeysChange,
        getCheckboxProps: (record: any) => ({
            disabled: record.status === 2 || record.status === 4, // Column configuration not to be checked
            name: record.coupon_meta_id,
        }),
    };
    const stopCouterFun = (stoplist) => {
        if (!stoplist || !stoplist.length) {
            message.warning('请选择需要作废的优惠券')
            return
        }
        return new Promise((resolve, reject) => {
            stopCouponFun(stoplist, (data) => {
                // console.log('data', data)
                // const upDataList = []
                data.forEach(res => {
                    if (!res.code) {
                        const upDataFind = goodsListData.find(item => item.coupon_meta_id === res.data.coupon_meta_id)
                        upDataFind && (upDataFind.status = 2)
                    }
                })
                setGoodsListData([...goodsListData])
                resolve(true)
            })
        })

    }
    return (<div>
        <Form
            size="small"
            name="getCouDataInfo"
            layout='inline'
        >
            <Form.Item label="优惠券名称/ID" style={{
                marginBottom: 10
            }}>
                <Input placeholder="请输入优惠券名称/ID" disabled={lodinDataStatus} value={getCouDataInfo.coupon_info} size="small" allowClear onChange={(e) => {
                    getCouDataInfo.coupon_info = e.target.value
                    setCouDataInfo({ ...getCouDataInfo })
                }} />
            </Form.Item>
            <Form.Item label="优惠券类型" style={{
                marginBottom: 10
            }}>
                <Select style={{ width: 200 }} disabled={lodinDataStatus} value={getCouDataInfo.coupon_type_group} size="small" onChange={(e: any) => {
                    getCouDataInfo.coupon_type_group = e
                    setCouDataInfo({ ...getCouDataInfo })
                }}>
                    <Option value="0">全部</Option>
                    <Option value="1">商品优惠券</Option>
                    <Option value="2">涨粉券</Option>
                    <Option value="3">达人专属券</Option>
                    <Option value="4">店铺新人券</Option>

                </Select>
            </Form.Item>
            <Form.Item label="优惠内容" style={{
                marginBottom: 10
            }}>
                <Select value={getCouDataInfo.favoured_type} disabled={lodinDataStatus} style={{ width: 200 }} size="small" onChange={(e: any) => {
                    getCouDataInfo.favoured_type = e
                    setCouDataInfo({ ...getCouDataInfo })
                }}>
                    <Option value="0">全部</Option>
                    <Option value="21">店铺折扣券</Option>
                    <Option value="22">店铺直减券</Option>
                    <Option value="23">店铺满减券</Option>
                    <Option value="41">指定商品折扣券</Option>
                    <Option value="42">指定商品直减券</Option>
                    <Option value="43">指定商品满减券</Option>
                </Select>
            </Form.Item>
            <Form.Item label="优惠券状态" style={{
                marginBottom: 10
            }}>
                <Select value={getCouDataInfo.status} disabled={lodinDataStatus} style={{ width: 200 }} size="small" onChange={(e: any) => {
                    getCouDataInfo.status = e
                    setCouDataInfo({ ...getCouDataInfo })
                }}>
                    <Option value="0">全部</Option>
                    <Option value="1">未生效</Option>
                    <Option value="2">已作废</Option>
                    <Option value="3">生效中</Option>
                    <Option value="4">已过期</Option>
                </Select>
            </Form.Item>
            <Form.Item label="领取时间" style={{
                marginBottom: 10
            }}>
                <DatePicker.DateRangePickerJoin disabled={lodinDataStatus} value={couponTime} size="small" onChange={(e: any) => {
                    setCouponTime(e)
                    if (!e) {
                        getCouDataInfo.start_apply_time = ''
                        getCouDataInfo.end_apply_time = ''
                    } else {
                        getCouDataInfo.start_apply_time = e[0].unix() + ''
                        getCouDataInfo.end_apply_time = e[1].unix() + ''
                    }
                    setCouDataInfo({ ...getCouDataInfo })
                }} />
            </Form.Item>
        </Form>
        <div className="getData" style={{
            margin: '10px 0 20px'
        }}>
            <Space>
                <Button type="primary" size="mini" disabled={lodinDataStatus} loading={lodinDataStatus} onClick={getCouponData}>查询</Button>
                <Button size="mini" disabled={lodinDataStatus} onClick={() => {
                    setCouponTime(null)
                    setCouDataInfo({ ...dataInfo })
                }}>重置</Button>
                <Button size="mini" danger type="primary" disabled={!selectGoodsKeys.length || stopCoupon} loading={stopCoupon} onClick={async () => {
                    seyLodinDataStatus(true)
                    setGoodsLoading(true)
                    setStopCoupon(true)
                    message.info('正在作废请稍后')
                    await stopCouterFun(selectGoodsKeys)
                    seyLodinDataStatus(false)
                    setGoodsLoading(false)
                    setStopCoupon(false)

                    message.success('已经全部作废')
                }}>批量作废</Button>
                <span style={{
                    fontSize: 12,
                    color: '#AEAEB2'
                }}>（仅未开始和进行中的优惠券可以作废）</span>
            </Space>

        </div>
        <Table
            loading={goodsLoading}
            // locale={{
            //     emptyText: <div>请加载商品列表<Button type="link" onClick={() => {
            //         // setAddCouponList(true)
            //         getProdectListFunAs()
            //     }}>加载</Button></div>
            // }}
            rowKey="coupon_meta_id"
            columns={goodsTitle}
            dataSource={goodsListData}
            bordered
            pagination={{
                pageSize: pageSize,
                // current: shearData.page + 1,
                pageSizeOptions: ['20', '50', '100', '200'],
                total: goodsDataInfoCont.total,
                // onShowSizeChange: (pageSize) => {
                //     console.log('pageSize', pageSize)
                // },
                onChange: (page, pageSize: any) => {
                    setPageSize(pageSize)
                    // console.log('修改页', page, pageSize)
                    // shearData.page = page - 1
                    // shearData.pageSize = pageSize
                    // setShearData({ ...shearData })
                    // getProdectListFunAs(shearData)
                },

                showTotal: (total, range) => {
                    return `共 ${total} 条数据`
                }
            }}
            scroll={{ y: 480 }}
            size='small'
            rowSelection={goodsSelectKeys}
        />
    </div>)
}
export default forwardRef(SetCoupon)